<html>
  <head>
    <style>
      body {
        margin: 0;
      }
    </style>
  </head>
  <body>
  <script src="three.js"></script>
  <script src="inflate.min.js"></script>
  <script src="FBXLoader.js"></script>
  <script>
    let cubes;
  
    const localVector = new THREE.Vector3();
    const localVector2 = new THREE.Vector3();
    const localQuaternion = new THREE.Quaternion();
    const localMatrix = new THREE.Matrix4();

    function init() {
      container = document.createElement('div');
      document.body.appendChild(container);

      camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 1000);
      camera.position.set(0, 0, 1);
      camera.lookAt(new THREE.Vector3());

      scene = new THREE.Scene();
      scene.matrixAutoUpdate = false;
      // scene.background = new THREE.Color(0x3B3961);

      const ambientLight = new THREE.AmbientLight(0x808080);
      scene.add(ambientLight);

      const directionalLight = new THREE.DirectionalLight(0xFFFFFF, 1);
      directionalLight.position.set(1, 1, 1);
      scene.add(directionalLight);

      const geometry = new THREE.BoxBufferGeometry(0.1, 0.05, 0.2);
      cubes = [0xFF0000, 0x00FF00, 0x0000FF, 0xFF0000, 0x00FF00, 0x0000FF, 0xFF0000, 0x00FF00, 0x0000FF, 0xFF0000].map((color, i) => {
        const material = new THREE.MeshPhongMaterial({
          color,
        });
        const mesh = new THREE.Mesh(geometry, material);
        mesh.position.x = -1 + i*0.2;
        mesh.updateMatrixWorld();
        mesh.frustumCulled = false;
        scene.add(mesh);
        return mesh;
      });

      renderer = new THREE.WebGLRenderer({ antialias: true });
      renderer.setPixelRatio(window.devicePixelRatio);
      renderer.setSize(window.innerWidth, window.innerHeight);
      container.appendChild(renderer.domElement);

      renderer.setAnimationLoop(animate);
    }

    function animate() {
      const gamepads = navigator.getGamepads();
      for (let i = 0; i < gamepads.length; i++) {
        const gamepad = gamepads[i];
        if (gamepad.connected) {
          const {pose} = gamepad;
          const cube = cubes[i];

          cube.matrix.compose(
            cube.position.fromArray(pose.position),
            cube.quaternion.fromArray(pose.orientation),
            cube.scale.set(1, 1, 1),
          );
          cube.updateMatrixWorld();
        }
      }

      renderer.render(scene, renderer.vr.enabled ? renderer.vr.getCamera(camera) : camera);
    }

    init();

    (async () => {
      console.log('request session');
      session = await navigator.xr.requestSession({
        exclusive: true,
      }).catch(err => Promise.resolve(null));

      if (session) {
        // console.log('request first frame');
        session.requestAnimationFrame((timestamp, frame) => {
          renderer.vr.setSession(session, {
            frameOfReferenceType: 'stage',
          });

          const {views} = frame.getViewerPose();
          const viewport = session.baseLayer.getViewport(views[0]);
          const width = viewport.width;
          const height = viewport.height;
          renderer.setSize(width * 2, height);

          renderer.setAnimationLoop(null);
          renderer.vr.enabled = true;
          renderer.vr.setAnimationLoop(animate);

          console.log('running!');
        });
      } else {
        console.log('no xr devices');
      }
    })();
  </script>
  </body>
</html>
